package org.example.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;

public class ChatSocketServerHandler extends ChannelInboundHandlerAdapter {
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress address = channel.remoteAddress();
        System.out.println(address + "----上线");
        group.writeAndFlush(address + "上线\n");
        group.add(channel);
    }

    /**
     * 断开连接事件
     *
     * @param ctx
     * @throws Exception
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        System.out.println(socketAddress + "------下线");
        // 返回客户端
        group.writeAndFlush(socketAddress + "下线，当前在线人数：" + group.size() + "\n");
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        for (Channel ch : group) {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + "：" + msg + "\n");
            } else {
                ch.writeAndFlush("me:" + msg + "\n");
            }
        }
    }


    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
    }


}
